<?php

namespace App\Http\Controllers\Admin\Base;

use App\Http\Controllers\Controller;
use App\Http\Requests\base\ExchangeRateRequest;
use App\Models\base\CurrencyModel;
use App\Models\base\ExchangeRateModel;
use Illuminate\Http\Request;

class ExchangeRate extends Controller
{
    use ExchangeRateRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $currency_id = $request->input('currency_id', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');


        $query = ExchangeRateModel::query()->with(['create_admin', 'currency_code']);

        if($currency_id){
            $query = $query->where('currency_id', $currency_id);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'currency_id' => $item->currency_id,
                'exchange_currency_id' => $item->exchange_currency_id,
                'currency_code' => $item->currency_code ? $item->currency_code->short_code : '',
                'exchange_currency_code' => $item->exchange_currency_code ? $item->exchange_currency_code->short_code : '',
                'rate' => $item->rate,
                'effect_time' => $item->effect_time,
                'invalid_time' => $item->invalid_time,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name : '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        if($params['currency_id'] == $params['exchange_currency_id']){
            return $this->error('原币种和换算币种不能相同');
        }

        $invalid_time_last = (new ExchangeRateModel())
            ->where('currency_id', $params['currency_id'])
            ->where('exchange_currency_id', $params['exchange_currency_id'])
            ->orderBy('invalid_time', 'desc')
            ->first();

        $model = new ExchangeRateModel();
        $model->currency_id = $params['currency_id'];
        $model->exchange_currency_id = $params['exchange_currency_id'];
        $model->rate = $params['rate'];
        $model->effect_time = $invalid_time_last ? $invalid_time_last ['invalid_time'] : date('Y-m-d H:i:s', time());
        $model->invalid_time = $params['invalid_time'];
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    public function update(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = ExchangeRateModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->currency_id = $params['currency_id'];
        $model->exchange_currency_id = $params['exchange_currency_id'];
        $model->rate = $params['rate'];
        $model->invalid_time = $params['invalid_time'];
        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = ExchangeRateModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }

    /**
     * Notes:
     * User: xiangzi
     * Date: 2024/11/6
     * Time: 下午3:45
     * @return void
     */
    public function turn($id, $turn_id, $amount = 0)
    {
        $time_now = date('Y-m-d H:i:s');
        $rate = ExchangeRateModel::where('currency_id', $id)
            ->where('exchange_currency_id', $turn_id)
            ->where('effect_time', '<', $time_now)
            ->where('invalid_time', '>=', $time_now)
            ->value('rate');

        $return = $amount;
        if($rate){
            $return = round($amount * $rate, 2);
        }
        return $return;
    }

    /**
     * Notes:获取CNY的汇率
     * @param Request $request
     * @return mixed
     */
    public function cny_rate() {
        $cny_id = CurrencyModel::where('short_code', 'CNY')->first()->id;

        $rate_find = ExchangeRateModel::where('exchange_currency_id', $cny_id)
            ->where('effect_time', '<', date('Y-m-d H:i:s'))
            ->where('invalid_time', '>=', date('Y-m-d H:i:s'))
            ->get();

        $rate[$cny_id] = [
            'symbol' => 'CNY',
            'rate' => 1,
        ];

        foreach ($rate_find as $item){
            $rate[$item->currency_id] = [
                'symbol' => CurrencyModel::find($item->currency_id)->short_code,
                'rate' => $item->rate,
            ];
        }

        return $rate;
    }

}
